//
//  AllViewController.m
//  LiTingFeng
//
//  Created by xinxuan on 16/1/25.
//  Copyright © 2016年 Bullgo. All rights reserved.
//

#import "AllViewController.h"
#import "TrainViewController.h"
#import "CustomViewController.h"
#import "PlayerViewController.h"
#import <AudioToolbox/AudioToolbox.h>
@interface AllViewController ()<UITableViewDelegate,UITableViewDataSource,EGORefreshTableHeaderDelegate,EGORefreshTableHeaderDelegate>

@property (nonatomic,strong)UITableView * tableView;

@property (nonatomic, strong) NSMutableArray *modelsArray;

@end

@implementation AllViewController

static NSString *reuseID = @"cell1";


- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"全部课程";
    [self getModelWithTitle];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    
    [self.view addSubview:self.tableView];
    
}




-(void)getModelWithTitle{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"allData.plist" ofType:nil];
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSArray * titleArray = [dic allKeys];
    NSMutableArray * dataArray = [NSMutableArray new];
    for (int i =0 ; i<titleArray.count ; i++) {
       NSArray *array = [dic objectForKey:titleArray[i]];
        [dataArray addObjectsFromArray:array];
    }
    
    _modelsArray = [NSMutableArray array];
    for (NSDictionary *dict in dataArray) {
        
        CommenModel *model = [CommenModel new];
        model.pic = dict[@"pic"];
        model.name = dict[@"name"];
        model.centent = dict[@"centent"];
        model.period = dict[@"period"];
        model.growth = dict[@"growth"];
        model.personNumber = dict[@"personNumber"];
        model.starCount = dict[@"starCount"];
        model.time = dict[@"time"];
        model.level = dict[@"level"];
        
        [self.modelsArray addObject:model];
        
    }
    
}




#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelsArray.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    BGTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
    cell.model = self.modelsArray[indexPath.row];
    
    return cell;
}



//随机数组

-(void)randomArray{
    
    NSArray *array = [NSArray arrayWithArray:_modelsArray];
    _modelsArray = [[NSMutableArray alloc]init];
    NSMutableSet *randomSet = [[NSMutableSet alloc] init];
    
    while ([randomSet count] < array.count) {
        int r = arc4random() % [array count];
        [randomSet addObject:[array objectAtIndex:r]];
    }
    
    _modelsArray = (NSMutableArray*)[randomSet allObjects];
    
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    CommenModel * model = [CommenModel new];
    model = _modelsArray[indexPath.row];
    
    
        
        NSString *string1 = model.name;
        NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 2)];
        if ([string2 isEqualToString:@"音乐"]) {
            PlayerViewController * playVC = [[PlayerViewController alloc]init];
            [self.navigationController pushViewController:playVC animated:YES];
        }else{
            TrainViewController * trainVc = [[TrainViewController alloc] init];
            trainVc.nameString = model.name;
            trainVc.detailString = model.centent;
            trainVc.totalTime = [model.time integerValue] * 60;
            [self.navigationController pushViewController:trainVc animated:YES];
        }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (Screen_Width == 320 && Screen_Height == 480) {//苹果4
        
        return 130;
        
    }else if(Screen_Width == 320 && Screen_Height == 568){//苹果5
        
        return 130;
        
        
    }else if(Screen_Width == 375 && Screen_Height == 667){//苹果6
        
        return 150;
        
        
    }else{//苹果6puls及其以上
        
        return 160;
        
    }
    
    
}



#pragma mark ---- 懒加载
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, Screen_Width, Screen_Height - 40 - 20 )];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = 0;
        [_tableView registerNib:[UINib nibWithNibName:@"BGTableViewCell" bundle:nil] forCellReuseIdentifier:reuseID];
    }
    if (_refreshHeaderView == nil) {
        
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _tableView.bounds.size.height, self.view.frame.size.width, _tableView.bounds.size.height)];
        view.delegate = self;
        [_tableView addSubview:view];
        _refreshHeaderView = view;
        
    }
    return _tableView;
}


#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
    _reloading = YES;
    
}

- (void)doneLoadingTableViewData{
    _reloading = NO;
    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}


#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    
}

#pragma mark EGORefreshTableHeaderDelegate Methods
//下拉到一定距离，手指放开时调用
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    
    [self reloadTableViewDataSource];
    
    //停止加载，弹回下拉
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:2.0];
    
    if (_barView == nil) {
        UIImage *img = [[UIImage imageNamed:@"timeline_new_status_background.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:5];
        _barView = [[UIImageView alloc] initWithImage:img];
        _barView.frame = CGRectMake(0, 40, Screen_Width, 40);
        [self.view addSubview:_barView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
        label.tag = 100;
        label.font = [UIFont systemFontOfSize:16.0f];
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor clearColor];
        [_barView addSubview:label];
        
    }
    UILabel *label = (UILabel *)[_barView viewWithTag:100];
    label.text = [NSString stringWithFormat:@"%d条按摩数据更新",10];
    [label sizeToFit];
    CGRect frame = label.frame;
    frame.origin = CGPointMake((_barView.frame.size.width - frame.size.width)/2, (_barView.frame.size.height - frame.size.height)/2);
    label.frame = frame;
    

    [self performSelector:@selector(updateUI) withObject:nil afterDelay:2.0];
    
}

- (void)updateUI {
    [UIView animateWithDuration:0.6 animations:^{
        CGRect frame = _barView.frame;
        frame.origin.y = 5;
        _barView.frame = frame;
    } completion:^(BOOL finished){
        if (finished) {
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDelay:1.0];
            [UIView setAnimationDuration:0.6];
            CGRect frame = _barView.frame;
            frame.origin.y = -40;
            _barView.frame = frame;
            [UIView commitAnimations];
        }
    }];

    
    [self randomArray];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"msgcome" ofType:@"wav"];
    NSURL *url = [NSURL fileURLWithPath:path];
    SystemSoundID soundId;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundId);
    AudioServicesPlaySystemSound(soundId);
    
    
    [_tableView reloadData];
    
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}

//取得下拉刷新的时间
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    
    return [NSDate date]; // should return date data source was last changed
    
}





- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [[NSNotificationCenter defaultCenter]postNotificationName:@"supportedInterfaceOrientations" object:self userInfo:@{@"surport" : [NSNumber numberWithBool:NO]}];
    self.tabBarController.tabBar.hidden = YES;
}


-(void)viewWillDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}


@end
